package com.um.springboot.starter.exception;

import com.um.springboot.starter.code.CommonCode;
import com.um.springboot.starter.orm.entity.Response;
import com.um.springboot.starter.service.impl.BaseService;
import com.um.springboot.starter.utils.SpringAsyncUtil;
import com.um.springboot.starter.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.connector.ClientAbortException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.server.ResponseStatusException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.Date;
import java.util.Hashtable;
import java.util.Map;

@Slf4j
@Order(100)
@ControllerAdvice
public class GlobalExceptionHandler {

    @Value("${spring.application.name:}")
    String applicationName;

    @Autowired
    BaseService baseService;

    @Autowired
    SpringAsyncUtil springAsyncUtil;

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Response handleException(HttpServletRequest req, HttpServletResponse rep, Exception e) {
        if (e instanceof ResponseStatusException) {
            throw (ResponseStatusException) e;
        }
        if (e instanceof ClientAbortException) {
            final String message = "ClientAbortException generated by request {} {} from remote address {} with X-FORWARDED-FOR {}";
            log.warn(message, req.getMethod(), req.getRequestURI(), req.getRemoteAddr(), req.getHeader("X-FORWARDED-FOR"));
            return null; //socket is closed, cannot return any response
        }

        ByteArrayOutputStream arrayOutput = new ByteArrayOutputStream();
        PrintStream pStream = new PrintStream(arrayOutput);
        e.printStackTrace(pStream);

        log.error("捕捉全局异常：", e);

        String uri = req.getRequestURI();
        String appName = StringUtil.isEmpty(applicationName) ? "" : applicationName + ":";

        Map<String, Object> errorLog = new Hashtable<>();
        if(uri != null && uri.contains("/")) {
            errorLog.put("action_name", appName + uri.substring(0, uri.lastIndexOf("/")));
            errorLog.put("method_name", uri.substring(uri.lastIndexOf("/")));
        }else{
            errorLog.put("action_name", appName);
            errorLog.put("method_name", "");
        }
        String parameters = (String)req.getAttribute("parameters");
        if(parameters == null)
            parameters = "[]";

        errorLog.put("parameters",parameters);
        errorLog.put("error_desc",e.toString());
        errorLog.put("error_log",arrayOutput.toString());
        errorLog.put("create_date",new Date());
        springAsyncUtil.run(() -> baseService.saveRecord("sys_error_log",errorLog));

        //TODO 统一记录错误信息到错误日志表
        return Response.failed(CommonCode.ServiceBusy);
    }
}
